import { createSlice, PayloadAction, createAsyncThunk } from "@reduxjs/toolkit";
import { getAlbums, getPhotos } from "@react-native-community/cameraroll";
import { PermissionsAndroid } from "react-native";

export interface AblumnCategoriesState {
    ablumnCategories: { title: string, count: number, coverUrl: string }[]
    loading: boolean; // 请求数据中
    error: string | null; // 是否错误
}



const initialState: AblumnCategoriesState = {
    ablumnCategories: [],
    loading: false,
    error: null,
};



export const getAblumCategories = createAsyncThunk<any, void>("getAblumCategories", async (params, { rejectWithValue }) => {
    const permission = PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE;
    const hasPermission = await PermissionsAndroid.check(permission);
    if(!hasPermission){
        const status = await PermissionsAndroid.request(permission);
        console.log(status);
        if(status !== "granted"){
            return rejectWithValue({
                code:-1,
                message:"未授权"
            });
        }
    }

    const res = await getAlbums({ assetType: "All" });
    // 拿到所有group的第一张图
    let proArr: (Promise<string>)[] = [];
    res.forEach(ablum => {
        proArr.push(getPhotos({
            first: 1,
            assetType: "All",
            groupName: ablum.title
        }).then(result => {

            return result.edges[0].node.image.uri;
        }));

    });

    const allCoverUrl = await Promise.all(proArr);
    let allAblumCategories: {
        count: number,
        title: string,
        coverUrl: string
    }[] = [];
    res.forEach((ablum, index) => {
        allAblumCategories.push({
            coverUrl: allCoverUrl[index],
            count: ablum.count,
            title: ablum.title
        });
    });
    return allAblumCategories;
}
);



export const AblumnCategoriesSlice = createSlice({
    name: "ablumnCategories",
    initialState,
    reducers:{},
    extraReducers: {
        [getAblumCategories.pending.type]: (state) => {
            state.loading = true;
        },
        [getAblumCategories.fulfilled.type]: (state, action) => {
            state.ablumnCategories = action.payload;
            state.loading = false;
        },
        [getAblumCategories.rejected.type]: (state, action: PayloadAction<string | null>) => {
            state.loading = false;
            state.error = action.payload;
        }
    }
});



